package com.hk.webapp.interceptors;

import com.hk.webapp.annotations.AllowAnonymous;
import com.hk.webapp.bo.UserBo;
import com.hk.webapp.custom.CustomMultipartHttpServletRequest;
import com.hk.webapp.error.BusinessErrorEnum;
import com.hk.webapp.error.BusinessException;
import com.hk.webapp.utils.JwtUtil;
import com.hk.webapp.vo.ResultVo;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;

/**
 * (C) Copyright 2017-now
 * All rights reserved.
 * <p>
 * JWT token拦截器
 *
 * @author DreamerCK
 * @date 2019-01-11 11:51
 **/
@Slf4j
@Order(1)
public class JwtInterceptor implements HandlerInterceptor {

    private String secretKey;

    public JwtInterceptor() {
    }

    public JwtInterceptor(String secretKey) {
        this.secretKey = secretKey;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info(request.getRequestURI());
        boolean nonKey = Optional.ofNullable(this.secretKey).isPresent();
        if (!nonKey) {
            return false;
        }
        String authorization = request.getHeader("Authorization");
        if (handler instanceof HandlerMethod) {
            AllowAnonymous perClass = (((HandlerMethod) handler).getBean().getClass().getAnnotation(AllowAnonymous.class));
            AllowAnonymous permission = ((HandlerMethod) handler).getMethod().getAnnotation(AllowAnonymous.class);
            if (StringUtils.isNotBlank(authorization)) {
                try {
                    UserBo userBo = JwtUtil.validateTokenAndAddUsernameToHeader(request, this.secretKey);
                    if (request instanceof JwtUtil.CustomHttpServletRequest) {
                        ((JwtUtil.CustomHttpServletRequest) request).setUsername(userBo.getUsername());
                        ((JwtUtil.CustomHttpServletRequest) request).setUserId(userBo.getUserId().toString());
                    } else {
                        ((CustomMultipartHttpServletRequest) request).setUsername(userBo.getUsername());
                        ((CustomMultipartHttpServletRequest) request).setUserId(userBo.getUserId().toString());
                    }
                    return true;
                } catch (BusinessException e) {
                    if (!Objects.isNull(perClass) || !Objects.isNull(permission)) {
                        return true;
                    }
                    ResultVo result = ResultVo.createByError(e.getErrMsg());
                    response.getWriter().write(JSON.toJSONString(result));
                    return false;
                }
            } else if (!Objects.isNull(perClass) || !Objects.isNull(permission)) {
                return true;
            }
            ResultVo result = ResultVo.createByErrorEnum(BusinessErrorEnum.LL_NEED_LOGIN);
            response.getWriter().write(JSON.toJSONString(result));
            return false;

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}